package com.syqc.monitor.ui.carinfo.report

import android.text.Html
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.syqc.adapter.AlarmHistoryAdapter
import com.syqc.comlib.base.LazyFragment
import com.syqc.comlib.callback.EmptyCallback
import com.syqc.comlib.rx.LiveDataBus
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.startActivityTo
import com.syqc.comlib.utils.toast
import com.syqc.entity.HistoryAlarm
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentReportAlarmBinding
import com.syqc.monitor.databinding.IncludeDayChooseBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.monitor.ui.alarm.AlarmDetailActivity
import com.syqc.monitor.ui.alarm.ReportSetModel
import com.syqc.monitor.ui.realalarm.AlarmChooseActivity2
import com.syqc.utils.AlarmDataUtil
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.utils.ToolsUtil.isFastClick
import com.syqc.videos.CarMonitorViewModel

/**
 *@Author Jasper
 *@Time   2020/10/15
 *@Desc   车辆报表
 */
class ReportAlarmFragment(private val isAdas: Boolean = false) :
    LazyFragment<FragmentReportAlarmBinding>(FragmentReportAlarmBinding::inflate) {
    private lateinit var loadService: LoadService<Any>
    private lateinit var mDayChooseVB: IncludeDayChooseBinding
    private lateinit var mSureVB: IncludeSelectSureBinding

    private val mActivityVM by activityViewModels<CarMonitorViewModel>()
    private val mViewModel: ReportAlarmViewModel by viewModels()

    private val alarmsAdapter by lazy { AlarmHistoryAdapter(true) }

    override fun initView(view: View) {

        if (ReportSetModel.instance.getNormalAlarmIds().isEmpty()
            || ReportSetModel.instance.getAdasAlarmIds().isEmpty()
        ) AlarmDataUtil.instance.getCarDefaultAlarm(isAdas)

        mViewModel.choose = getString(R.string.desc_selected)
        binding.editRunTime.setText(ReportSetModel.instance.getSpeed(isAdas))
        binding.editRunTime.setSelection(binding.editRunTime.text.length)
        binding.editLongTime.setText(ReportSetModel.instance.getContinueTime(isAdas))
        binding.editLongTime.setSelection(binding.editLongTime.text.length)
        binding.lrTvCarSetAlarm.setRightText(Html.fromHtml(mViewModel.getAlarmIds(isAdas)))
        binding.llAlarmType.isVisible = false

        mSureVB = IncludeSelectSureBinding.bind(binding.root)
        mDayChooseVB = IncludeDayChooseBinding.bind(binding.root)
        mSureVB.tvSure.setText(R.string.desc_sure_query)
        mViewModel.isAdas = isAdas
        loadService = LoadSir.getDefault().register(binding.includeRecycler.recyclerView)

        mActivityVM.carName.observe(this) {
            mViewModel.carName = it
        }

        mActivityVM.carId.observe(this) {
            if (it.isNullOrEmpty()) {
                loadService.showCallback(EmptyCallback::class.java)
            } else {
                mViewModel.carId = it
                if (!mViewModel.isHidden) mViewModel.handleTime()
            }
        }
    }

    override fun initData() {
        if (mViewModel.carId.isEmpty()) showToast(R.string.hint_toast_choose_car)
        loadService.showCallback(EmptyCallback::class.java)

        LiveDataBus.get().with("AlarmChoose", String::class.java).observeStick(this) {
            binding.lrTvCarSetAlarm.setRightText(Html.fromHtml(mViewModel.getAlarmIds(isAdas)))
        }

        initRecycler()

        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        mViewModel.alarmSub.hide().autoDispose(scopeProvider).subscribe {
            if (it.list.isNullOrEmpty()) {
                binding.llAlarmType.isVisible = false
                loadService.showCallback(EmptyCallback::class.java)
            } else {
                binding.llAlarmType.isVisible = true
                loadService.showSuccess()
                alarmsAdapter.setList(it.list)
            }
        }
    }

    override fun initEvent() {
        binding.editRunTime.doAfterChanged {
            if (it.isEmpty()) {
                ReportSetModel.instance.setSpeed("0", isAdas)
            } else {
                ReportSetModel.instance.setSpeed(it, isAdas)
            }

        }

        binding.editLongTime.doAfterChanged {
            if (it.isEmpty()) {
                ReportSetModel.instance.setContinueTime("0", isAdas)
            } else {
                ReportSetModel.instance.setContinueTime(it, isAdas)
            }

        }

        mSureVB.tvSure.setOnClickListener {
            binding.ivOpenClose.isSelected = false
            binding.llAlarmCondition.isVisible = false
            if (!mViewModel.isHidden && mViewModel.carId.isNotEmpty()) mViewModel.handleTime()
            ReportSetModel.instance.saveParams()

            if (binding.editRunTime.text.isEmpty()) {
                binding.editRunTime.setText("0")
            }

            if (binding.editLongTime.text.isEmpty()) {
                binding.editLongTime.setText("0")
            }
        }

        binding.llQueryCondition.setOnClickListener {
            binding.ivOpenClose.isSelected = !binding.ivOpenClose.isSelected
            binding.llAlarmCondition.isVisible = binding.ivOpenClose.isSelected
        }

        binding.lrTvCarSetAlarm.filterFast {
            val ids = if (isAdas) {
                ReportSetModel.instance.getAdasAlarmIds()
            } else {
                ReportSetModel.instance.getNormalAlarmIds()
            }
            startActivityTo<AlarmChooseActivity2>(requireContext()) {
                putExtra(Keys.INTENT_OTHER, isAdas)
                putExtra(Keys.INTENT_DATA, ids)
                putExtra(Keys.INTENT_TYPE, true)
            }
        }

        mDayChooseVB.rdbReportYesterday.setOnClickListener {
            mViewModel.timeType = 1
            mViewModel.handleTime()
        }

        mDayChooseVB.rdbReportToday.setOnClickListener {
            mViewModel.timeType = 2
            mViewModel.handleTime()
        }

        mDayChooseVB.rdbReportThree.setOnClickListener {
            mViewModel.timeType = 3
            mViewModel.handleTime()
        }

        mDayChooseVB.rdbReportWeek.setOnClickListener {
            mViewModel.timeType = 4
            mViewModel.handleTime()
        }
    }

    private fun initRecycler() {
        binding.includeRecycler.recyclerView.layoutManager = LinearLayoutManager(requireContext())

        binding.includeRecycler.recyclerView.adapter = alarmsAdapter.apply {
            setOnItemClickListener { adapter, view, position ->
                if (isFastClick()) return@setOnItemClickListener
                val info = adapter.data[position] as HistoryAlarm.TotalAlarms
                if (info.total == 0) {
                    R.string.toast_no_about_alarm.toast(requireContext())
                } else {
                    startActivityTo<AlarmDetailActivity>(requireContext()) {
                        putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
                        putExtra(Keys.INTENT_PLATE, info.name)
                        putExtra(Keys.INTENT_TITLE, "${info.name}(${info.total})")
                        DataUtil.alarmInfo = info.list
                    }
                }
            }
        }
    }

    //是否隐藏状态变化监听
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (hidden) {
            mViewModel.isHidden = true
        } else {
            mViewModel.isHidden = false
            if (mViewModel.carId.isNotEmpty()) mViewModel.handleTime()
        }
    }

}